<script setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import api from '@/api/index.js'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  },
  faMenuSltOpt: {
    type: Array,
    default: () => ([])
  },
})
// 权限树结构
const treeData = ref([])
// 树结构选择项
const checkedKeys = ref([])
// 弹窗标题
const title = ref('角色授权')
// 获取角色详情
const getRoleInfo = async (val) => {
  const { resultObject: { roleMenus } } = await api.getRoleInfo({ id: val.id })
  checkedKeys.value = roleMenus.map(item => item.menu)
}
// 同步表格数据到表单数据内
watch(() => props.curRow, (val) => {
  val?.id && (getRoleInfo(val))
}, { deep: true, immediate: true })
// 是否显示弹窗
const show = ref(false);
// 弹窗显示状态切换时触发
const afterOpenChange = bool => {
  if (!bool) {
    checkedKeys.value = []
    emits('close')
  }
};
// 清空权限
const sltEmpty = () => {
  checkedKeys.value = []
}
// 全选权限
const sltAll = () => {
  const allIds = []
  function getId (list = []) {
    if (list?.length > 0) {
      list.forEach(item => {
        allIds.push(item.id)
        if (item.children) {
          getId(item.children)
        }
      })
    }
  }
  getId(treeData.value)
  const keys = [...new Set(allIds)]
  checkedKeys.value = keys
}
// 获取权限树结构
const getAuthTree = async () => {
  const { resultObject } = await api.getMenuList()
  treeData.value = resultObject
}
// 打开弹窗
const open = () => {
  show.value = true;
  getAuthTree()
};
// 关闭弹窗
const close = () => {
  show.value = false
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 修改权限
const roleAddPer = async () => {
  submitLoading.value = true
  const params = {
    role: props.curRow.id,
    menus: checkedKeys.value.checked || checkedKeys.value
  }
  await api.roleAddPer(params)
  message.success('保存成功')
  close()
  setTimeout(() => {
    submitLoading.value = false
  }, 30);
}
defineExpose({ open })
</script>

<template>
  <a-drawer :maskClosable="false" :closable="false" destroyOnClose v-model:open="show" class="custom-class" root-class-name="root-class-name" :title="title"
    placement="right" @after-open-change="afterOpenChange">
    <a-tree v-model:checkedKeys="checkedKeys" checkable :tree-data="treeData" v-if="treeData.length" defaultExpandAll
      checkStrictly :fieldNames="{ children: 'children', title: 'name', key: 'id' }">
    </a-tree>
    <template #footer>
      <div style="display: flex;gap: 5px;">
        <a-button type="primary" @click="roleAddPer" :loading="submitLoading"
          :disabled="checkedKeys?.checked?.length === 0 || checkedKeys?.length === 0">提交</a-button>
        <a-button type="primary" ghost @click="close">取消</a-button>
        <a-button type="link" ghost @click="sltAll">全选</a-button>
        <a-button type="link" ghost @click="sltEmpty">清空</a-button>
      </div>
    </template>
  </a-drawer>
</template>
